package com.xiqing.wechat.web.controller;

import com.xiqing.wechat.entity.token.JsApiInfo;
import com.xiqing.wechat.service.token.AccessTokenService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by wanglijun on 17/1/5.
 */
@Controller
public class JsTicketController {



    @Autowired
    private AccessTokenService accessTokenService;

    @RequestMapping("/getInfo")
    @ResponseBody
        public String  getInfo(@Param(value = "state") String state, HttpServletRequest request) {
            //跨域获取jsapi相关信息
            String url = request.getParameter("url");
            String callback = request.getParameter("callback");
            JsApiInfo info = accessTokenService.getJsTicket (url);
            return setJsInfo(info, callback);
        }


        private String setJsInfo(JsApiInfo info, String callback) {
            if (null != info) {
                StringBuffer sb = new StringBuffer();
                if (StringUtils.isNotEmpty(callback))
                    sb.append(callback + "(");
                sb.append("{\"appId\":\"" + info.getAppId() + "\"");
                sb.append(",\"timestamp\":\"" + info.getTimestamp() + "\"");
                sb.append(",\"nonceStr\":\"" + info.getNonceStr() + "\"");
                sb.append(",\"signature\":\"" + info.getSignature() + "\"}");
                if (StringUtils.isNotEmpty(callback))
                    sb.append(callback + ")");
            return sb.toString();
        }
        return StringUtils.EMPTY;
    }



    @RequestMapping
    @ResponseBody
    public String getTicket(@Param(value = "state") String state, HttpServletRequest request){
        OkHttpClient client = new OkHttpClient();

        Request requestOK = new Request.Builder()
                .url("http://api.parllay.cn/v1.1/social/wxconfig/7UOHYCCD9T/metadata/get?url=http%3A%2F%2Fwww.baidu.com&access_token=VL88poNAF6VVXvlIG6tMpii45U8D_bu97R7M2hVqb-WJYNNZ7SH66eNywa8ZMJ-2L6gU7mcRh3JraXspy2JSugVkGiWsLslszmZymuRytig")
                .get()
                .addHeader("cache-control", "no-cache")
                .addHeader("postman-token", "8fae5de5-9699-08a4-0a0d-89a6c9c1b4a5")
                .build();

        Response response = null;
        try {
            response = client.newCall(requestOK).execute();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return response.body ().toString ();
    }



}
